package com.xh.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xh.mapper.PostersMapper;
import com.xh.model.enums.DeletedEnum;
import com.xh.model.request.PosterSaveRequest;
import com.xh.model.request.PreviewRequest;
import com.xh.model.response.PosterResponse;
import com.xh.model.response.Posters;
import com.xh.model.table.Poster;
import com.xh.model.table.PosterItem;
import com.xh.service.PosterItemsService;
import com.xh.service.PostersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 海报记录表 服务实现类
 * </p>
 *
 * @author wen
 * @since 2021-07-08
 */
@Service
public class PostersServiceImpl extends ServiceImpl<PostersMapper, Poster> implements PostersService {

    @Autowired
    private PosterItemsService posterItemsService;

    @Override
    @Transactional
    public Long save(PreviewRequest request) {
        Poster poster;
        if (Objects.isNull(request.getId()) || request.getId() <= 0) {    // 新增
            // 新增海报主表记录
            poster = request.buildAdd();
            // TODO 设置海报列表图片
//            poster.setBgUrl();
            this.baseMapper.insert(poster);
        } else {     // 修改
            Poster dbPosters = this.baseMapper.selectById(request.getId());
            Assert.isFalse(Objects.isNull(dbPosters), ("未找到海报数据"));
            // 删除已有得海报明细
            posterItemsService.deleteByPosterId(dbPosters.getId());
            // 修改操作
            poster = request.buildUpdate();
            this.baseMapper.updateById(poster);
        }
        // 新增海报明细记录
        List<PosterItem> posterItems = request.buildPosterItems(request, poster);
        posterItemsService.saveBatch(posterItems);
        return poster.getId();
    }

    @Override
    public Long save(PosterSaveRequest request) {
        PreviewRequest req = request.convert();
        return this.save(req);
    }

    @Override
    public List<Posters> getList() {
        // 查询海报记录
        LambdaQueryWrapper<Poster> eq = Wrappers.lambdaQuery(Poster.class)
                .eq(Poster::getDeleted, Boolean.FALSE)
                .orderByDesc(Poster::getCreateTime);
        List<Poster> posters = this.baseMapper.selectList(eq);
        // 通过海报记录ID集合查询海报组件记录
        Set<Long> posterIds = posters.stream().map(Poster::getId).collect(Collectors.toSet());
        List<PosterItem> itemList = posterItemsService.list(Wrappers.lambdaQuery(PosterItem.class)
                .in(PosterItem::getPosterId, posterIds));
        Map<Long, List<PosterItem>> groupMap = itemList.stream().collect(Collectors.groupingBy(PosterItem::getPosterId));
        // 构建响应数据
        return PosterResponse.build(posters, groupMap);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        // 删除海报记录
        Poster poster = new Poster();
        poster.setId(id);
        poster.setDeleted(DeletedEnum.STATUS_1.getValue());
        int res = this.baseMapper.updateById(poster);
        // 删除已有得海报明细
        if (res > 0) {
            posterItemsService.deleteByPosterId(id);
        }
    }

    @Override
    @Transactional
    public Long copy(Long id) {
        Poster poster = this.baseMapper.selectById(id);
        Assert.isFalse(Objects.isNull(poster), ("未找到海报数据"));
        List<PosterItem> itemList = posterItemsService.list(Wrappers.lambdaQuery(PosterItem.class)
                .eq(PosterItem::getPosterId, poster.getId()));
        // 设置新ID，新增海报记录
        poster.setId(IdWorker.getId());
        LocalDateTime now = LocalDateTime.now();
        poster.setCreateTime(now);
        poster.setUpdateTime(now);
        int res = this.baseMapper.insert(poster);
        // 新增海报组件记录
        if (res > 0 && CollUtil.isNotEmpty(itemList)) {
            itemList.forEach(item -> {
                item.setId(IdWorker.getId());
                item.setPosterId(poster.getId());
            });
            posterItemsService.saveBatch(itemList);
        }
        return poster.getId();
    }

}
